package com.hontech.desktoppastacooker.ui.activity

import android.content.pm.PackageManager
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.hontech.desktoppastacooker.utils.await
import com.hontech.desktoppastacooker.utils.getLocationInWindowRect
import kotlinx.coroutines.CompletableDeferred

open class BaseActivity : AppCompatActivity() {

    companion object {

        lateinit var INSTANCE: BaseActivity

        fun rootView(): View {
            return INSTANCE.window.decorView
        }
    }

    private var permissionFuture: CompletableDeferred<Boolean>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        INSTANCE = this
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_UP) {
            pressUp(ev)
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun pressUp(ev: MotionEvent) {
        val view = currentFocus ?: return
        if (view !is EditText) {
            return
        }
        val x = ev.rawX.toInt()
        val y = ev.rawY.toInt()

        val rect = view.getLocationInWindowRect()
        if (rect.contains(x, y)) {
            return
        }
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    suspend fun requestPermission(permission: String) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            return
        }
        permissionFuture = CompletableDeferred()
        requestPermissions(arrayOf(permission), 0)
        val ret = permissionFuture!!.await(30 * 1000)
        if (!ret) {
            throw IllegalStateException("没有授权读写访问")
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty()) {
            permissionFuture?.complete( grantResults[0] == PackageManager.PERMISSION_GRANTED )
        }
    }
}